import {Directive, DirectiveBinding, nextTick} from 'vue';

const lazyLoadHandler = (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const lazyImage = entry.target as HTMLImageElement;
            const src = lazyImage.dataset.src!;
            lazyImage.src = src;
            lazyImage.onload = () => {
                lazyImage.removeAttribute('data-src');
                observer.unobserve(lazyImage);
            };
            lazyImage.onerror = () => {
                const errorSrc = lazyImage.dataset.errorSrc!;
                if (errorSrc) {
                    lazyImage.src = errorSrc;
                }
                lazyImage.removeAttribute('data-src');
                observer.unobserve(lazyImage);
            };
        }
    });
};

const lazyLoadOptions: IntersectionObserverInit = {
    root: null,
    threshold: 0.5,
    rootMargin: '0px',
};
export const LazyDirective: Directive<HTMLImageElement> = {
    beforeMount(el: HTMLImageElement, binding: DirectiveBinding) {
        if (binding.value) {
            const defaultLoadingSrc: string = 'https://img.zcool.cn/community/013c045ba069dfa801213dea31d786.gif';
            const defaultErrorSrc: string = 'https://www.lilang.online/file/images/default-error.webp';
            el.dataset.src = binding.value;
            el.dataset.loadingSrc = el.src || defaultLoadingSrc;
            el.dataset.errorSrc = defaultErrorSrc;
            el.src = el.dataset.loadingSrc;
            setTimeout(() => {
                const observer = new IntersectionObserver(lazyLoadHandler, lazyLoadOptions);
                observer.observe(el);
            }, 100)
        }
    },
};

export default LazyDirective;
